package com.hzncc.flowable_diboot.controller.sales;

import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.util.IamSecurityUtils;
import com.hzncc.flowable_diboot.dto.BusinessDTO;
import com.hzncc.flowable_diboot.entity.Business;
import com.hzncc.flowable_diboot.mapper.OppoFlowOrderMapper;
import com.hzncc.flowable_diboot.service.BusinessService;
import com.hzncc.flowable_diboot.vo.BusinessDetailVO;
import com.hzncc.flowable_diboot.vo.BusinessListVO;
import com.hzncc.flowable_diboot.vo.OppoFlowOrderDetailVO;
import com.hzncc.flowable_diboot.vo.OppoFlowOrderItemDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* 商机 相关rest接口
* @author MyName
* @version 1.0
* @date 2024-06-06
* Copyright © MyCorp
*/
@Slf4j
@RequestMapping("/business")
@BindPermission(name = "商机")
@RestController
public class BusinessController extends BaseCrudRestController<Business> {

    @Autowired
    private BusinessService businessService;

    @Autowired
    private OppoFlowOrderMapper oppoFlowOrderMapper;

    /**
    * 查询资源对象的列表VO记录
    * <p>
    * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
    * </p>
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<BusinessListVO>> getListVOMapping(BusinessDTO queryDto, Pagination pagination,String type) throws Exception {
        List<BusinessListVO> list = businessService.selectBusiness(queryDto, pagination, type);
        for (BusinessListVO datum : list) {
            if (datum.getStarUids() != null && datum.getStarUids().contains(IamSecurityUtils.getCurrentUserId())) {
                datum.setIsStar(1);
            } else {
                datum.setIsStar(0);
            }
        }
        return JsonResult.OK(list).bindPagination(pagination);
    }

    /**
    * 根据id查询资源对象的详情VO
    * @param id ID
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<BusinessDetailVO> getDetailVOMapping(@PathVariable("id")String id) throws Exception {
        BusinessDetailVO detailVO = businessService.getViewObject(id, BusinessDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
    * 创建资源对象数据
    * @param business
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<?> createModelMapping(@RequestBody Business business) throws Exception {
        businessService.create(business);
        //boolean success = businessService.createEntity(business);
        //log.debug("新建数据 商机:{} {}", business.getId(), success? "成功":"失败");
        return JsonResult.OK(business.getId());
    }

    /**
    * 批量创建资源对象数据
    * @param businessList
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch")
    public JsonResult<?> batchCreateModelMapping(@RequestBody List<Business> businessList) throws Exception {
        boolean success = businessService.createEntities(businessList);
        log.debug("批量新建数据 商机 {}", success? "成功":"失败");
        return JsonResult.OK(success);
    }

    /**
    * 根据id更新资源对象
    * @param business
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id")String id, @RequestBody Business business) throws Exception {
        boolean success = businessService.updateEntity(business);
        log.debug("更新数据 商机:{} {}", id, success? "成功":"失败");
        return JsonResult.OK(success);
    }

    /**
    * 根据id删除资源对象
    * @param id
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = businessService.deleteEntity(id);
        oppoFlowOrderMapper.delByBusIds(Collections.singletonList(id));
        log.debug("删除数据 商机:{} {}", id, success? "成功":"失败");
        return JsonResult.OK(success);
    }

    /**
    * 根据ids集合删除资源对象
    * @param ids
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = businessService.deleteEntities(ids);
        oppoFlowOrderMapper.delByBusIds(ids);
        log.debug("批量删除数据 商机:{} {}", ids, success? "成功":"失败");
        return JsonResult.OK(success);
    }

    /**
     * 查询流程单
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/11
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/flow")
    public JsonResult<?> selectFlowOrder(String id){
        OppoFlowOrderDetailVO oppoFlowOrderDetailVO = businessService.selectFlowOrder(id);
        return JsonResult.OK(oppoFlowOrderDetailVO);
    }

    /**
     * 流程提交
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/11
     */
    @Log(operation = OperationCons.LABEL_WRITE)
    @BindPermission(name = OperationCons.LABEL_WRITE, code = OperationCons.CODE_WRITE)
    @PostMapping("/flow-commit")
    public JsonResult<?> flowCommit(@RequestBody OppoFlowOrderItemDetailVO item){
        return businessService.flowCommit(item,item.getRes());
    }

    /**
     * 流程暂存
     *
     * @return
     * @author 陈广煜
     * @date 2024/7/9
     */
    @Log(operation = OperationCons.LABEL_WRITE)
    @BindPermission(name = OperationCons.LABEL_WRITE, code = OperationCons.CODE_WRITE)
    @PostMapping("/flow-stage")
    public JsonResult<?> staging(@RequestBody OppoFlowOrderItemDetailVO item){
        return businessService.flowStage(item);
    }

    /**
     * 商机关注
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/13
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @GetMapping("/star")
    public JsonResult<?> star(String cid) {
        String uid = IamSecurityUtils.getCurrentUserId();
        Business entity = businessService.getViewObject(cid, BusinessListVO.class);
        List<String> starUids = entity.getStarUids();
        if (starUids == null){
            entity.setStarUids(Collections.singletonList(uid));
        }else {
            starUids.add(uid);
        }
        businessService.updateEntity(entity);
        return JsonResult.OK();
    }

    /**
     * 商机取关
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/13
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @GetMapping("/cancel")
    public JsonResult<?> cancel(String cid) {
        String uid = IamSecurityUtils.getCurrentUserId();
        Business entity = businessService.getViewObject(cid, BusinessListVO.class);
        entity.setStarUids(entity.getStarUids().stream().filter(e -> !Objects.equals(uid, e)).collect(Collectors.toList()));
        businessService.updateEntity(entity);
        return JsonResult.OK();
    }
}